
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.RepaintManager;




public class PrintUtil implements Printable {
private Component componettobeprinted;
public static void printcomponet(Component c){
new PrintUtil(c).print();
}
public PrintUtil(Component cpd){
this.componettobeprinted=cpd;
}

public void print(){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setCopies(1);
pj.setPrintable(this);

if(pj.printDialog()){
            try {
                pj.print();
            } catch (PrinterException ex) {
                Logger.getLogger(PrintUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
}

}
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
      if(pageIndex>0){
          return (NO_SUCH_PAGE);
      }else{
      Graphics2D g = (Graphics2D)graphics;
 g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
      disableDoubleBuff(componettobeprinted);
      componettobeprinted.paint(g);
      enabledoubleBuff(componettobeprinted);
      return(PAGE_EXISTS);
      }
    }
public static void disableDoubleBuff(Component c){
RepaintManager currm = RepaintManager.currentManager(c);
currm.setDoubleBufferingEnabled(false);
}
public static void enabledoubleBuff(Component c){
RepaintManager cur= RepaintManager.currentManager(c);
cur.setDoubleBufferingEnabled(true);
}
}
